<template>
  <div class="gdMap">
    <a-button v-if="locations==null || locations.length <= 0 || locations=='[]'" type="primary" @click="showModal">{{ type == 1 ? '绘制点位' : '绘制范围' }}</a-button>
    <a-button v-else type="primary" @click="showModal">{{ '已绘制' }}</a-button>
    <a-modal
      v-model="visible"
      title="Map"
      on-ok="handleOk"
      width="820px"
      :destroyOnClose="true"
      @cancel="cancel"
      @ok="handleOk"
    >
      <div class="map-content">
        <div class="tools" v-if="!disabled">
          <div class="tools-search">
            <a-input placeholder="请输入关键字" style="width: 300px" id="tipinput" allowClear />
            <a-button type="primary" style="margin-left: 10px" @click="prevMarker">回退</a-button>
            <a-button type="dashed" style="margin-left: 10px" @click="clearMarker">清除</a-button>
          </div>
          <div style="margin-top: 10px; display: flex; align-items: center">
            <a-button @click="startPoint">{{ type == 1 ? '开始打点' : '开始绘制' }}</a-button>
            <a-button style="margin-left: 14px" @click="endPoint">{{ type == 1 ? '结束打点' : '结束绘制' }}</a-button>
            <div class="handle_input">
              <div class="input_lng">
                <div class="input_lng_name">经度:</div>
                <div class="input_lng_input">
                  <a-input
                    placeholder="请输入经度"
                    type="number"
                    :value="handelLng"
                    @change="inputLng"
                    style="width: 150px"
                    allowClear
                  />
                </div>
              </div>
              <div class="input_lng">
                <div class="input_lng_name">维度:</div>
                <div class="input_lng_input">
                  <a-input
                    placeholder="请输入维度"
                    type="number"
                    :value="handelLat"
                    @change="inputLat"
                    style="width: 150px"
                    allowClear
                  />
                </div>
              </div>
              <a-button type="primary" style="margin-left: 10px" @click="handledefine">定位</a-button>
            </div>
          </div>
        </div>
        <div class="layers">
          <a-select default-value="wx" style="width: 105px" @change="changeLayers">
            <a-select-option :value="item.label" v-for="item in options" :key="item.id">{{
              item.name
            }}</a-select-option>
          </a-select>
        </div>
        <div id="ditu" v-if="visible"></div>
      </div>
    </a-modal>
  </div>
</template>
<script>
export default {
  model: {
    prop: 'locations',
    event: 'change',
  },
  props: {
    type: {
      type: [String, Number],
      default: 1,
    },
    locations: {
      type: String,
      default: '',
    },
    disabled: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      loading: false,
      visible: false,
      lng: 117.237465,
      lat: 31.818724,
      options: [
        {
          id: 1,
          label: 'cg',
          name: '常规地图',
        },
        {
          id: 2,
          label: 'wx',
          name: '卫星图',
        },
      ],
      timer: null,
      map: null,
      status: false, //是否可以打点的状态
      markers: [], // 点位信息
      paths: [], //多边形信息
      selectPath: null, //当前操作的多边形
      mapPoint: [], //点位经纬度
      mapPath: [], //区域点位信息
      searchValue: '',
      tips: [''],
      clearStatus: false, // 清除的状态标识
      handelLng: '',
      handelLat: '',
    }
  },
  beforeDestory() {
    this.locations = []
    this.mapPoint = []
    this.mapPath = []
    this.map.off('click', this.addPoint)
    console.log('销毁走了没=======')
  },
  created() {},
  mounted() {
    this.mapPoint = []
    this.mapPath = []
    if(this.locations==null) {
      this.locations = []
    }
    console.log('传过来的值===', this.locations)
  },
  methods: {
    handledefine() {
      console.log('确定定位')

      if (this.disabled) return
      if (!this.status) {
        return this.$message.warning(`请先点击开始${this.type == 1 ? '打点' : '绘制'}按钮进行打点`)
      }
      if (this.handelLng.length == 0 || this.handelLat.length == 0) {
        return this.$message.warning('请输入经纬度')
      }
      const _location = {
        lng: this.handelLng,
        lat: this.handelLat,
      }
      this.showMarkers(_location)
      //点位打点 type 1
      const location = {
        lng: _location.lng,
        lat: _location.lat,
      }
      var markerPosition = [_location.lng, _location.lat]
      this.map.panTo(markerPosition)
      this.mapPoint.push(location)
      this.handelLng = ''
      this.handelLat = ''
      if (this.type == 2) {
        //重新进行
        this.drawPaths(this.mapPoint)
      }
    },
    inputLng(e) {
      console.log('经度=====', e)
      this.handelLng = e.target.value
    },
    inputLat(e) {
      console.log('维度=====', e)
      this.handelLat = e.target.value
    },
    changeLayers(value) {
      if (value === 'wx') {
        this.map.setLayers([new AMap.TileLayer.Satellite(), new AMap.TileLayer.RoadNet()])
      } else {
        this.map.setLayers([new AMap.TileLayer()])
      }
    },
    //开始打点
    startPoint() {
      this.$message.success(`成功激活${this.type == 1 ? '打点' : '绘制区域'}功能`)
      this.status = true
    },
    //结束打点
    endPoint() {
      this.$message.success(`成功消除${this.type == 1 ? '打点' : '绘制区域'}功能`)
      this.status = false
      if (this.type == 2) {
        //记录上一次数据
        this.paths.push(this.selectPath)
        this.mapPath.push(this.mapPoint)
        //清空上一次数据
        this.selectPath = null
        this.mapPoint = []
      }
    },
    addPoint(event) {
      if (this.disabled) return
      if (!this.status) {
        return this.$message.warning(`请先点击开始${this.type == 1 ? '打点' : '绘制'}按钮进行打点`)
      }
      console.log(event)
      const _location = event.lnglat
      this.showMarkers(_location)
      //点位打点 type 1
      const location = {
        lng: _location.lng,
        lat: _location.lat,
      }
      this.mapPoint.push(location)
      if (this.type == 2) {
        //重新进行
        this.drawPaths(this.mapPoint)
      }
    },
    //展示markers
    showMarkers(location) {
      // 创建 AMap.Icon 实例：
      const icon = new AMap.Icon({
        size: new AMap.Size(30, 30), // 图标尺寸
        image: require('../../assets/location.png'), // Icon的图像
        imageSize: new AMap.Size(30, 30), // 根据所设置的大小拉伸或压缩图片
      })
      const marker = new AMap.Marker({
        position: new AMap.LngLat(location.lng, location.lat),
        offset: new AMap.Pixel(-15, -15),
        icon: icon, // 添加 Icon 图标 URL
      })
      this.map.add(marker)
      this.markers.push(marker)
    },
    //绘制区域
    drawPaths(mapPoint) {
      if (this.selectPath) this.map.remove(this.selectPath)
      let path = []
      mapPoint.map((item) => {
        const obj = new AMap.LngLat(item.lng, item.lat)
        path.push(obj)
      })
      this.selectPath = new AMap.Polygon({
        path: path,
        fillColor: '#1890ff', // 多边形填充颜色
        fillOpacity: 0.3,
        borderWeight: 1, // 线条宽度，默认为 1
        strokeColor: '#1890ff', // 线条颜色
      })
      this.map.add(this.selectPath)
    },
    //回退
    prevMarker() {
      if (this.markers.length == 0) {
        return this.$message.warning('点位已清空')
      }
      const _prevPoint = this.markers[this.markers.length - 1]
      //移除点位
      this.map.remove(_prevPoint)
      //删除数据里的数据
      this.markers.splice(this.markers.length - 1, 1)
      if (this.type == 1) {
        this.mapPoint.splice(this.mapPoint.length - 1, 1)
      } else if (this.type == 2) {
        //如果当前多边形点位信息消除为空，重置一个新的
        if (this.mapPoint.length == 0) {
          if (this.mapPath.length > 0) {
            const _index = this.mapPath.length - 1
            this.mapPoint = this._.cloneDeep(this.mapPath[_index])
            //paths 消除最后一个
            this.map.remove(this.paths[_index])
            this.paths.splice(_index, 1)
            this.mapPath.splice(_index, 1)
          }
        }
        this.mapPoint.splice(this.mapPoint.length - 1, 1)
        this.drawPaths(this.mapPoint)
      }
    },
    //清楚所有
    clearMarker() {
      const _this = this
      this.$confirm({
        title: '提示',
        content: '是否删除地图所有的标记信息?',
        onOk() {
          //删除所有点位
          if (_this.markers) _this.map.remove(_this.markers)
          _this.markers = []
          if (_this.paths) _this.map.remove(_this.paths)
          _this.paths = []
          if (_this.selectPath) _this.map.remove(_this.selectPath)
          //点位清空
          _this.mapPoint = []
          _this.mapPath = []
          _this.selectPath = null
          _this.clearStatus = true
        },
      })
    },
    onSelectTip(e) {
      const placeSearch = new AMap.PlaceSearch({
        map: this.map,
      }) // 构造地点查询类
      placeSearch.setCity(e.poi.adcode)
      placeSearch.search(e.poi.name)
    },
    showLocalPoint(e) {
      this.clearMarker()
      this.mapPoint = [e.lnglat.getLng(), e.lnglat.getLat()]
      this.marker = new AMap.Marker({
        icon: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png',
        position: [e.lnglat.getLng(), e.lnglat.getLat()],
        offset: new AMap.Pixel(-13, -30),
      })
      this.marker.setMap(this.map)
    },
    showModal() {
      const _this = this
      this.visible = true
      console.log("点击没效果");
      this.$nextTick(() => {
        this.map = new AMap.Map('ditu', {
          resizeEnable: true, // 是否监控地图容器尺寸变化
          zoom: 14, // 初始化地图层级
          center: [this.lng, this.lat], // 初始化地图中心点
          layers: [
            new AMap.TileLayer.Satellite(),
            // 路网
            new AMap.TileLayer.RoadNet(),
          ],
          doubleClickZoom: false,
        })
        // 使用天地图测试
        // this.wms = new AMap.TileLayer.WMTS({
        //   url: 'http://t4.tianditu.gov.cn/img_w/wmts',
        //   blend: false,
        //   tileSize: 256,
        //   params: {
        //     Layer: 'img',
        //     Version: '1.3.0',
        //     Format: 'tiles',
        //     TileMatrixSet: 'w',
        //     STYLE: 'default',
        //     tk: '天地图的key',
        //   },
        // })

        // this.wms.setMap(this.map)
        //输入提示
        const auto = new AMap.Autocomplete({
          input: 'tipinput',
        })
        AMap.event.addListener(auto, 'select', this.onSelectTip)
        this.mapPoint = []
        this.mapPath = []
        //绑定初始化时间
        this.init()
        console.log('this.locations---', this.locations)
        //定位数据没有，获取当前网络定位
        if (this.locations == '' || this.locations == null || this.locations == []) {
          console.log('有数据吗111===', this.locations)
          AMap.plugin('AMap.Geolocation', function () {
            const geolocation = new AMap.Geolocation({
              enableHighAccuracy: true, //是否使用高精度定位，默认:true
              timeout: 10000, //超过10秒后停止定位，默认：5s
              buttonPosition: 'RB', //定位按钮的停靠位置
              buttonOffset: new AMap.Pixel(10, 20), //定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
              zoomToAccuracy: true, //定位成功后是否自动调整地图视野到定位点
            })
            geolocation.getCurrentPosition(function (status, result) {
              console.log('定位数据什什么======', status, result)
              if (status == 'complete') {
                const { lng, lat } = result.position
                const _center = new AMap.LngLat(lng, lat)
                _this.lng = lng
                _this.lat = lat
                _this.map.setCenter(_center)
              } else {
                _this.$message.error('定位失败')
              }
            })
          })
        } else {
          console.log('有数据吗222===', this.locations)
          const _locations = JSON.parse(this.locations)
          let lng = '',
            lat = ''
          if (this.type == 1) {
            const _location = _locations[0]
            lng = _location.lng
            lat = _location.lat
          } else {
            const _location = _locations[0][0]
            lng = _location.lng
            lat = _location.lat
          }
          const _center = new AMap.LngLat(lng, lat)
          _this.lng = lng
          _this.lat = lat
          _this.map.setCenter(_center)
        }
      })
    },
    //绑定事件
    init() {
      //初始化信息
      this.map.on('click', this.addPoint)
      //初始化信息数据
      if (this.locations != '' && this.locations != null && this.locations.length > 0) {
        const _location = JSON.parse(this.locations)
        console.log('_location==', _location)
        //如果是打点
        if (this.type == 1) {
          for (let i = 0; i < _location.length; i++) {
            this.showMarkers(_location[i])
            this.mapPoint = _location
          }
        } else {
          for (let i = 0; i < _location.length; i++) {
            _location[i].map((item) => {
              this.showMarkers(item)
            })
            this.drawPaths(_location[i])
            this.paths.push(this.selectPath)
            this.selectPath = null
          }
          this.mapPath = _location
          console.log('赋值========', this.mapPath)
        }
      }
    },
    //取消
    cancel() {
      this.status = false
      this.markers = []
      this.paths = []
      this.selectPath = null
      this.mapPoint = []
      this.mapPath = []
    },
    //确定
    handleOk() {
      console.log('确定的按钮=====')
      if (this.status) {
        return this.$message.warning(
          `请点击结束${this.type == 1 ? '打点' : '绘制'}按钮终止地图${this.type == 1 ? '打点' : '绘制'}操作`
        )
      }
      // 如果没有清除且原来有数据,将原来的数据和新打点的数据合并，并且去除重复数据
      if (!this.clearStatus && this.locations) {
        console.log('this.locations1', JSON.stringify(this.locations))
        this.mapPoint = [...JSON.parse(this.locations), ...this.mapPoint]
        this.mapPoint = this.mapPoint.filter((x, index, self) => {
          let arrLngs = []
          let arrLats = []
          this.mapPoint.forEach((item, i) => {
            arrLngs.push(item.lng)
            arrLats.push(item.lat)
          })
          let judgeLng = arrLngs.indexOf(x.lng) === index
          let judgeLat = arrLats.indexOf(x.lat) === index
          return judgeLng || judgeLat
        })
        console.log('this.mapPoint', JSON.stringify(this.mapPoint))
        console.log('this.locations', JSON.stringify(this.locations))
        JSON.stringify(this.location)
      }
      this.visible = false
      //点位
      if (this.type == 1) {
        this.$emit('change', JSON.stringify(this.mapPoint))
      } else {
        this.$emit('change', JSON.stringify(this.mapPath))
      }
    },
  },
}
</script>
<style scoped lang="less">
.map-content {
  position: relative;
  width: 100%;
  height: 600px;

  .tools {
    position: absolute;
    width: 100%;
    top: 10px;
    left: 10px;
    margin-bottom: 16px;
    z-index: 11;

    .tools-search {
      display: flex;
    }

    .tools-area {
      display: flex;
    }

    ::v-deep .ant-mentions {
      width: 300px;
    }
  }

  .layers {
    position: absolute;
    top: 10px;
    right: 10px;
    z-index: 11;
  }

  #ditu {
    width: 100%;
    height: 600px;
  }
}
.handle_input {
  display: flex;
  align-items: center;
  margin-left: 20px;
  .input_lng {
    display: flex;
    align-items: center;
    margin-right: 20px;
    background: #fff;
    padding: 0 10px;
    box-sizing: border-box;
    border-radius: 5px;
    .input_lng_name {
      font-size: 14px;
    }
    .input_lng_input {
      flex: 1;
      ::v-deep .ant-input {
        border: none !important;
        box-shadow: none !important;
      }
    }
  }
}
</style>
<style>
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
  -webkit-appearance: none;
}
input[type='number'] {
  -moz-appearance: textfield;
}
</style>
